﻿using System;
using System.Linq;
using WorkLogger.Client.DataAccess.Model;
using WorkLogger.Client.Forms;

namespace WorkLogger.Client.Commands {
	public class TickCommand : ICommand {
		private readonly AppOptions appOptions;
		private readonly IWorkDayManager workDayManager;
		private readonly WorkTimeCalculator workTimeCalculator;
		private readonly ISystemClock systemClock;

		public TickCommand(AppOptions appOptions,
		                   IWorkDayManager workDayManager,
		                   WorkTimeCalculator workTimeCalculator,
		                   ISystemClock systemClock) {
			this.appOptions = appOptions;
			this.workDayManager = workDayManager;
			this.workTimeCalculator = workTimeCalculator;
			this.systemClock = systemClock;
		}

		public void Execute() {
			WorkDay currentWorkDay = workDayManager.GetCurrentWorkDay();

			TryAddStandartLunch(currentWorkDay);

			currentWorkDay.EndWork = systemClock.Now;
			currentWorkDay.LastWorkMoment = systemClock.Now;

			if (currentWorkDay.EndWorkingNotified == false) {
				TimeSpan workedTime = workTimeCalculator.GetWorkedTime(currentWorkDay);
				if (workedTime >= appOptions.WorkDayDuration.GetTimeSpan()) {
					using (var form = new EndWorkForm()) {
						form.WorkedTime = workedTime;
						currentWorkDay.EndWorkingNotified = true;
						workDayManager.Update();
						form.ShowDialog();
					}
				}
			}

			workDayManager.Update();
		}

		private void TryAddStandartLunch(WorkDay currentWorkDay) {
			if (appOptions.WorkDayDuration.Hours <= 4)
				return;
			double workedMinutes = workTimeCalculator.GetWorkedTime(currentWorkDay).TotalMinutes;
			double allWorkDayMinutes = appOptions.WorkDayDuration.GetTimeSpan().TotalMinutes;
			if (workedMinutes <= allWorkDayMinutes*0.66)
				return;
			double lunchTimeDuration = workTimeCalculator.GetLunchTime(currentWorkDay).TotalMinutes;
			if (lunchTimeDuration >= 30)
				return;

			DateTime workDate = currentWorkDay.WorkDate;
			var startLunch = new DateTime(workDate.Year, workDate.Month, workDate.Day, 12, 0, 0);
			DateTime endLunch = startLunch.AddMinutes(30);
			if (currentWorkDay.LunchTimes.Any()) {
				LunchTime lunchTime = currentWorkDay.LunchTimes.First();
				lunchTime.EndLunch = lunchTime.EndLunch.AddMinutes(30 - lunchTimeDuration);
			} else {
				currentWorkDay.LunchTimes.Add(new LunchTime {
				                                            	StartLunch = startLunch,
				                                            	EndLunch = endLunch,
				                                            	WorkDay = currentWorkDay
				                                            });
			}
		}
	}
}